#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File    : bootstrap.py
@Author  : Spring
@Time    : 2024/12/11 10:36
@Desc    : 初始相关s
"""
import logging
import os

import jpype

from watermark.heart_beat.heart_beat_service import HeartBeatService
from watermark.water_mark.watermark_service import WatermarkService

logger = logging.getLogger(__name__)


class BootstrapInitializer(type):
    def __init__(cls, name, bases, dct):
        super().__init__(name, bases, dct)
        jar_path = cls.get_jar_path()
        cls.do_start(jar_path)
        HeartBeatService.initialize()
        WatermarkService.initialize()


class Bootstrap(metaclass=BootstrapInitializer):
    """
    初始化相关类
    """

    @classmethod
    def start(cls):
        cls.do_start(cls.get_jar_path())

    @classmethod
    def do_start(cls, jar_path: str):
        """
        启动jvm，加载jdbc驱动
        :return:
        """
        if not jpype.isJVMStarted():
            jvm_path = jpype.getDefaultJVMPath()
            args = []
            # 加载jar
            # class_path = ['D:\\work\\development\\GuangFa\\sdk\\target'
            #               '\\venus-dms-sdk-1.0-SNAPSHOT-jar-with-dependencies.jar']
            class_path = [jar_path]
            args.append('-Djava.class.path=%s' % os.path.pathsep.join(class_path))
            jpype.startJVM(jvm_path, *args)
            is_jvm_started = jpype.isJVMStarted()
            logger.info('jvm启动状态: %s', is_jvm_started)

    @classmethod
    def stop(cls):
        """
        关闭JVM
        :return:
        """
        if jpype.isJVMStarted():
            jpype.shutdownJVM()

    @classmethod
    def get_jar_path(cls) -> str:
        """
        获取jar包路径
        :return:
        """
        current_dir = os.path.dirname(os.path.abspath(__file__))
        parent_dir = os.path.dirname(current_dir)
        # 定位到资源目录
        resources_dir = os.path.join(parent_dir, 'resource')
        # 构建资源文件路径
        file_path = os.path.join(resources_dir, 'DMS-SDK.jar')
        return file_path
